<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/3
 * Time: 15:55
 */

namespace App\HttpController\V1;


use App\HttpController\Taoran\Functions\Publics;
use App\Tools\Token\Token;
use EasySwoole\EasySwoole\Config;

class Scien extends BaseWithDb
{
    protected $param;   //参数
    protected $searchTime;   //查询条件时间
    protected $limit = 10;  //每页条数
    protected $offset = 0;  //查询起步点
    protected $userId;
    function onRequest( ?string $action ): ?bool
    {
        $returnRequest = parent::onRequest( $action );
        $this->param = $this->input();

//        if ( !Checking::keyIsExistence( 'page', $this->param ) ) {
//            $this->writeJson( -1, null, Checking::MESSAGE['keyIsExistence'] );
//            return false;
//        }
        if (isset($this->param['page'])){
            $this->offset = ( $this->param['page'] - 1 ) * $this->limit;
        }
        $jwt = $this->request()->getHeader( Config::getInstance()->getConf( 'TOKEN_NAME' ) )[0]??'';
        if (!empty( $jwt ) ){
            $data = Token::decode( $jwt );
            $this->userId=$data['content']->id;
        }else{
            $this->userId=0;
        }
        #判断前端是否传过来时间
        if ( isset( $this->param['time'] ) && !empty( $this->param['time'] ) ) {
            $days = date( 't', strtotime( $this->param['time'] ) );
            $startTime = $this->param['time'] . '-01';
            $endTime = $this->param['time'] . '-' . $days . ' 23:59:59';
        } else {
            $startTime = date( 'Y-m' ) . '-01';
            $days = date( 't', strtotime( $startTime ) );
            $endTime = date( 'Y-m' ) . '-' . $days . ' 23:59:59';
        }
        $this->searchTime = [$startTime, $endTime];

        return $returnRequest;
    }
    /**
     * 列表
     * input :type 0全部 class 1名师更多 2文章 3国学 4大学生 5问答  auth_id 名师id 0全部
     */
    public function artice_list(){
        $input=$this->input();
        try{
            if (!in_array($input['class'],[1,2,3,4,5])){
                return $this->writeJson(201,null,'参数异常');
            }
            $snow=new Snow();
            $class_id=$this->db->where('pid',$snow->log_type($input['class']))->getColumn('study_class','id');
            switch ($input['type']){
                case 0:#全部类型
                    if (!empty($class_id)){
                        $this->db=$this->db->whereIn('class_id',array_values($class_id));
                    }
                    break;
                default:
                    if (!in_array($input['type'],$class_id)){
                        return $this->writeJson(202,null,'类型错误');
                    }
                    $this->db=$this->db->where('class_id',$input['type']);
                    break;
            }
            if (isset($input['auth_id'])){
                switch ($input['auth_id']){
                    case 0:#全部类型

                        break;
                    default:
//                        if (!in_array($input['auth_id'],$class_id)){
//                            return $this->writeJson(202,null,'类型错误');
//                        }
                        if (isset($input['auth_id'])){
                            $this->db=$this->db->where('author_id',$input['auth_id']);
                        }
                        break;
                }
            }

            $field=$snow->log_field($input['class']);
            $list['list']=$this->db
                ->orderBy('create_time','DESC')
                ->get('study',[$this->offset,$this->limit],$field);
            foreach ($list['list'] as $k=>$v){
                if (isset($v['image'])){
                    $list['list'][$k]['image']=$this->video_url.$v['image'];
                }

                if (isset($v['author_id'])){
                    $list['list'][$k]['user_info']=$this->db
                        ->where('id',$v['author_id'])
                        ->getOne('study_author');
                }
                if (!in_array($input['class'],[1])){
                    if($this->userId>0){
                        $users_collection=$this->db
                            ->where('study_id',$v['id'])
                            ->where('user_id',$this->userId)
                            ->getOne('users_collection');
                        if (!empty($users_collection)){
                            $info=1;#已收藏
                        }else{
                            $info=0;
                        }
                        $list['list'][$k]['is_collection']=$info;
                        $list['list'][$k]['is_like']=$snow->likes($this->db,$v['id'],$this->userId);
                    }else{
                        $list['list'][$k]['is_collection']=0;
                        $list['list'][$k]['is_like']=0;
                    }
//                    $list['list'][$k]['is_like']=$snow->likes($this->db,$v['id'],$this->userId);
//                    $list['list'][$k]['is_collection']=$snow->likes($this->db,$v['id'],$this->userId);
                }
                if (isset($list['list'][$k]['content'])){
                    $list['list'][$k]['content']=mb_substr($list['list'][$k]['content'],0,100).'...';
                }
                #查询用户信息
                if (isset($v['user_id'])){
                    $list['list'][$k]['user_info']=$this->db
                        ->where('id',$v['user_id'])
                        ->getOne('users','id,headimg,nickname');
                    $list['list'][$k]['user_info']['headimg']=$this->video_url.$list['list'][$k]['user_info']['headimg'];
                }
            }
            return $this->writeJson(200,$list);
        }catch (\Exception $exception){
            return $this->writeJson($exception->getCode(),$exception->getMessage());
        }
    }

    /**
     * 名师列表
     */
    function ming_list(){
        $page=$this->getPage();
        $data=$this->db->orderBy('id','desc')->get('study_author',$page);
        foreach ($data as $k=>&$v){
            $v['headimg']=QINIU_URL.$v['headimg'];
        }
        return $this->writeJson(200,$data,'ok');
    }

    /**
     * 名师分类
     *
     */
    public function ming_class(){
        $data['study_class']=$this->db->where('pid',5)->get('study_class');
        $table_name = '`study_author` as b';
        $data['study_auth'] = $this->db
            ->join('`study` as a','a.author_id = b.id')
            ->get($table_name,null,'b.id,b.author');
        $data['study_auth']=$this->array_unique_fb($data['study_auth']);
        $data['study_auth']=array_values($data['study_auth']);
        return $this->writeJson(200,$data,'ok');
    }

    function array_unique_fb($array2D){
        foreach ($array2D as $k=>$v){
            $v=join(',',$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[$k]=$v;
        }
        $temp=array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
        foreach ($temp as $k => $v){
            $array=explode(',',$v); //再将拆开的数组重新组装
            //下面的索引根据自己的情况进行修改即可
            $temp2[$k]['id'] =$array[0];
            $temp2[$k]['author'] =$array[1];
        }
        return $temp2;
    }

    function array_unset_tt($arr,$key){
        //建立一个目标数组
        $res = array();
        foreach ($arr as $value) {
            //查看有没有重复项
            if(isset($res[$value[$key]])){
                unset($value[$key]);  //有：销毁
            }else{
                $res[$value[$key]] = $value;
            }
        }
        return $res;
    }

    /**
     * 名师首页
     */
    public function troops(){
        #1,名师轮播图
        $data['banner']=$this->db->where('type',2)->orderBy('sort','desc')->get('banner',null,'id,image,link,createdtime');
        foreach ($data['banner'] as &$vc){
            $vc['image']=($vc['image'])?$this->video_url.$vc['image']:'';
        }
        #2,名师推荐
        $data['teacher']=$this->db->where('type',1)->get('study_author',null,'id,author,headimg');
        foreach ($data['teacher'] as &$vv){
            $vv['headimg']=($vv['headimg']!='')?$this->video_url.$vv['headimg']:'';
        }
        $class=$this->db->where('pid',5)->getColumn('study_class','id');
        $filed='id,study_title,author_id,image,time,browse,create_time';
        $data['content']=$this->db
            ->where('is_good',1)
            ->whereIn('class_id',$class)
            ->orderBy('create_time','DESC')
//            ->orderBy('weigh','DESC')
            ->get('study',[$this->offset,$this->limit],$filed);
        foreach ($data['content'] as $k=>$v){
            $data['content'][$k]['image']=$this->video_url.$v['image'];
            $author=$this->db->where('id',$v['author_id'])->getOne('study_author','id,author,author_identity');
            $data['content'][$k]['author_id']=$author['id'];
            $data['content'][$k]['author']=$author['author'];
            $data['content'][$k]['author_identity']=$author['author_identity'];
        }
        return $this->writeJson(200,$data);
    }
    /**
     * 专访、读书
     * type 1专访，2读书
     * class: 6专访 44，7读书 45
     */
    public function book_list(){
        $input=$this->input();
        switch ($input['type']){
            case 1:
                $field='id,study_title,introduce,image,time,create_time,browse';
                $this->db=$this->db->where('class_id',44);
                break;
            case 2:
                $field='id,study_title,introduce,image,time,create_time,browse';
                $this->db=$this->db->where('class_id',45);
                break;
            default:
                $field='*';
                break;
        }
        $list['list']=$this->db
            ->orderBy('create_time','DESC')
            ->get('study',[$this->offset,$this->limit],$field);
        foreach ($list['list'] as $k=>$v){
            if ($k<1){
                $list['one']=$v;
                if (isset($v['image'])){
                    $list['one']['image']=$this->video_url.$v['image'];
                }
            }
            $list['list'][$k]['image']=$this->video_url.$v['image'];
        }
        return $this->writeJson(200,$list,'ok');

    }
    /**
     * 名师分享,人物专访,读书（书籍精讲）
     * input:study_id 文章id
     */
    public function troops_show(){
        $input=$this->input();
        try{
            $snow= new Snow();
            $snow->browseinc($this->db,$input['study_id']);
            $table_name = '`study` as b';
            $list = $this->db
                ->where('b.id',$input['study_id'])
                ->join('`study_author` as a','a.id = b.author_id','LEFT')
                ->get($table_name,null,'b.id,b.share_text,b.study_title,b.introduce,b.content,b.comm_num,b.class_id,b.author_id,b.image,b.vip_video,b.user_id,b.time,browse,b.create_time');
            foreach ($list as $k=>&$v){
                $v['image']=($v['image']!='')?$this->video_url.$v['image']:'';
                $v['vip_video']=($v['vip_video']!='')?$this->video_url.$v['vip_video']:'';
//                if ($v['class_id']==44){
//                    $user_id=$v['user_id'];
//                }else{
                $user_id=$v['author_id'];
//                }
                if ($v['class_id']==44){
                    $vip=$this->is_vip();
                }
            }
            #名师资料
            if (isset($user_id)&&$user_id>0){
                $user=$this->db->where('id',$user_id)->getOne('study_author');
                if ($user['headimg']!=''||$user['headimg']!=null){
                    $user['headimg']=$this->video_url.$user['headimg'];
                }
                $userifor=$this->db->where('pid',7)->get('study_class','id');
                $userids=array_column($userifor,'id');
                if (in_array($list[0]['class_id'],$userids)){
                    $user['author_introduce']=$list[0]['introduce'];
                }
            }else{
                $user=[];
            }
            if (isset($vip)){
                $data=[
                    'list'=>$list,
                    'userinfo'=>$user,
                    'vip_info'=>$vip
                ];
                if ($vip=='' || empty($vip)){
                    unset($data['vip_info']);
                }
            }else{
                $data=[
                    'list'=>$list,
                    'userinfo'=>$user,
                ];
            }
            return $this->writeJson(200,$data);
        }catch (\Exception $exception){
            return $this->writeJson($exception->getCode(),'',$exception->getMessage());
        }
    }
    /**
     * 国学详情
     * input:study_id 国学id
     */
    public function ancient_detail(){
        $input=$this->input();
        try{
            $list = $this->db
                ->where('id',$input['study_id'])
                ->getOne('study','id,class_id,study_title,share_text,image,vip_video,name,time,browse,favorite,introduce,create_time');
            if ($list['vip_video']!=''){
                $list['vip_video']=$this->video_url.$list['vip_video'];
            }
            $snow=new Snow();
            $snow->setinc_l($this->db,$list['id']);
            $datail=$this->db
                ->where('class_id',$list['class_id'])
                ->where('study_title',$list['study_title'])
                ->orderBy('weigh','asc')
                ->get('study',null,'id,study_title,image,share_text,user_video,name,time,browse,favorite,introduce,create_time');
            $name=array_column($datail,'name');
            $id=array_column($datail,'id');
            $names=array_combine($id,$name);
            $snow=new Snow();

            $list['image']=$this->video_url.$list['image'];
            if($this->userId>0){
                $users_collection=$this->db
                    ->where('study_id',$input['study_id'])
                    ->where('user_id',$this->userId)
                    ->getOne('users_collection');
//        dump($users_collection);
                if (!empty($users_collection)){
                    $is_collectioninfo=1;#已收藏
                }else{
                    $is_collectioninfo=0;
                }
                $info['is_collection']=$is_collectioninfo;
                $info['is_like']=$snow->likes($this->db,$input['study_id'],$this->userId);
                //TODO: 上下集未写
                #判断VIP到期时间
                $vip=$this->db->where('id',$this->userId)->getValue('users','vip_expire_time');
                $vip_stop=strtotime($vip)-time();
                $day_stop=ceil($vip_stop/86400);
            }else{
                $info['is_collection']=0;
                $info['is_like']=0;
                $day_stop=0;
            }
            $namess=[];
            foreach ($names as $k=>$v){
                $namess[$k]['title']=$v;
                $namess[$k]['id']=$k;
            }
            $namess=array_values($namess);
            return $this->writeJson(200,['list'=>$list,'info'=>$info,'name'=>$namess,'vip'=>$day_stop]);
        }catch (\Exception $exception){
            return $this->writeJson($exception->getCode(),'',$exception->getMessage());
        }
    }

    /**
     * 问答详情
     */
    public function answers(){
        $input=$this->input();
        try{
            $list = $this->db
                ->where('id',$input['study_id'])
                ->getOne('study','id,user_id,study_title,class_id,content,browse,favorite,`like`,image,comm_num,create_time');
            if (empty($list)){
                return $this->writeJson(201,'','问答不存在');
            }
            $snow=new Snow();
            $snow->setinc_l($this->db,$list['id']);
            if ($this->userId>0){
                $users_collection=$this->db
                    ->where('study_id',$input['study_id'])
                    ->where('user_id',$this->userId)
                    ->getOne('users_collection');
                if (!empty($users_collection)){
                    $collectioninfo=1;#已收藏
                }else{
                    $collectioninfo=0;
                }
                $list['is_collection']=$collectioninfo;
                $list['is_like']=$snow->likes($this->db,$input['study_id'],$this->userId);
                $list['is_follow']=$snow->follow($this->db,$list['user_id'],$this->userId);
            }else{
                $list['is_collection']=0;
                $list['is_like']=0;
                $list['is_follow']=0;
            }
            $list['users_info']=$this->db->where('id',$list['user_id'])->getOne('users','id,nickname,headimg');
            $list['users_info']['headimg']=$this->video_url.$list['users_info']['headimg'];

            $page=1;
            $page_size=10;
            $Publics=new Publics();
            $id=$input['study_id'];      //  study_id
//            $study_ids=$this->db->where('study_id',$id)->
            $info=$this->db->where('study_id',$id)->orderBy('id')->get('study_comment',[($page-1)*$page_size,$page_size],'*');

            foreach ($info as $k=>&$v){
                $v['create_time']=$Publics->get_last_time($v['create_time']);
                $user=$this->db->where('id',$v['user_id'])->getOne('users','headimg,nickname');
                $v['user_headimg']=QINIU_URL.$user['headimg'];
                $v['user_nickname']=$user['nickname'];
                if($v['to_user_id']){
                    $to_user=$this->db->where('id',$v['to_user_id'])->getOne('users','headimg,nickname');
                    $to_user_content=$this->db->where('id',$v['pid'])->getValue('study_comment','content');
                    $v['to_user_info']['user_headimg']=QINIU_URL.$to_user['headimg'];
                    $v['to_user_info']['user_nickname']=$to_user['nickname'];
                    $v['to_user_info']['user_content']=$to_user_content;
                }
            }
            return $this->writeJson(200,['list'=>$list,'info'=>'','pl'=>$info]);
        }catch (\Exception $exception){
            return $this->writeJson($exception->getCode(),'',$exception->getMessage());
        }
    }
    /**
     * 问答搜索
     * input: search
     */
    public function search(){
        $input=$this->input();
        $snow=new Snow();
        $search=preg_replace('# #', '', $input['search']);
        if ($this->userId>0){
            if ($search!=''){
                $data=[
                    'search_detail'=>$input['search'],
                    'user_id'=>$this->userId,
                    'create_time'=>date('Y-m-d H:i:s',time())
                ];
                $is_has=$this->db->where('user_id',$this->userId)->where('search_detail',$input['search'])->getOne('search');
                if (empty($is_has)){
                    $this->db->insert('search',$data);
                }else{
                    $this->db->where('user_id',$this->userId)->where('search_detail',$input['search'])->update('search',['create_time'=>date('Y-m-d H:i:s',time())]);
                }
            }
        }
        $class_id=$this->db->where('pid',$snow->log_type(5))->getColumn('study_class','id');
        $field=$snow->log_field(5);
        $list=$this->db
            ->whereIn('class_id',$class_id)
            ->whereLike('study_title','%'.$input['search'].'%')
            ->whereLike('content','%'.$input['search'].'%','OR')
            ->orderBy('create_time','desc')
            ->get('study',[$this->offset,$this->limit],$field);
        foreach ($list as $k=>$v){
            if ($this->userId>0){
                $list[$k]['is_like']=$snow->likes($this->db,$v['id'],$this->userId);
                $list[$k]['is_collection']=$snow->collection($this->db,$v['id'],$this->userId);
            }else{
                $list[$k]['is_like']=0;
                $list[$k]['is_collection']=0;
            }
            if ($v['image']!=''){
                $list[$k]['image']=$this->video_url.$v['image'];
            }else{
                $list[$k]['image']=null;
            }
            $list[$k]['users_info']=$this->db->where('id',$v['user_id'])->getOne('users','id,nickname,headimg');
            $list[$k]['users_info']['headimg']=$this->video_url.$list[$k]['users_info']['headimg'];
        }
        return $this->writeJson(200,$list);
    }

    /**
     * 搜索记录
     */
    public function search_log(){
        if ($this->userId>0){
            $log= $this->db->where('user_id',$this->userId)->orderBy('create_time','desc')->get('search',[0,5],'search_detail,create_time');
        }else{
            $log=[];
        }
        return $this->writeJson(200,$log,'ok');
    }

    /**
     * 文章详情
     */
    public function artice_detail(){
        $input=$this->input();
        try{
            $list = $this->db
                ->where('id',$input['study_id'])
                ->getOne('study','id,study_title,image,share_text,content,user_video,time,browse,`like`,favorite,comm_num,create_time');
            $snow=new Snow();
            $snow->setinc_l($this->db,$list['id']);
            $list['image']=$this->video_url.$list['image'];
            if ($this->userId>0){
                $info['is_like']=$snow->likes($this->db,$input['study_id'],$this->userId);
                $users_collection=$this->db
                    ->where('study_id',$input['study_id'])
                    ->where('user_id',$this->userId)
                    ->getOne('users_collection');
//        dump($users_collection);
                if (!empty($users_collection)){
                    $is_collectioninfo=1;#已收藏
                }else{
                    $is_collectioninfo=0;
                }
                $info['is_collection']= $is_collectioninfo;
            }else{
                $info['is_like']=0;
                $info['is_collection']=0;
            }
            $vip=$this->is_vip();
            return $this->writeJson(200,['list'=>$list,'info'=>$info,'vip'=>$vip]);
        }catch (\Exception $exception){
            return $this->writeJson($exception->getCode(),'',$exception->getMessage());
        }
    }
    /**
     * 在线看书
     */
    public function content(){
        $input=$this->input();
        $content = $this->db
            ->where('id',$input['study_id'])
            ->getValue('study','content');
        return $this->writeJson(200,$content);
    }

    /**
     * 名师详情
     * input: troops_id名师id
     */
    public function troops_detail(){
        $input=$this->input();
        try{
            $table_name = '`study` as b';
            $list = $this->db
                ->where('b.author_id',$input['troops_id'])
                ->join('`study_author` as a','a.id = b.author_id')
                ->get($table_name,null,'b.id,b.share_text,b.study_title,b.image,b.time,browse');
            foreach ($list as $k=>$v){
                $list[$k]['image']=$this->video_url.$v['image'];
            }
            #名师资料
            $user=$this->db->where('id',$input['troops_id'])->getOne('study_author');
            $user['headimg']=$this->video_url.'/'.$user['headimg'];
            return $this->writeJson(200,['list'=>$list,'userinfo'=>$user]);
        }catch (\Exception $exception){
            return $this->writeJson($exception->getCode(),'',$exception->getMessage());
        }
    }

    /**
     * vip
     */
    public function is_vip(){
        $jwt = $this->request()->getHeader( Config::getInstance()->getConf( 'TOKEN_NAME' ) )[0]??'';
        $data = Token::decode( $jwt );
        $userId = $data['content'];
        $vip_expire_time= $this->db->where('id',$userId)->getValue('users','vip_expire_time');
        $vip_type= $this->db->where('id',$userId)->getValue('users','level');
        $vip=strtotime($vip_expire_time);
        $time=time();
        $new_time=$vip-$time;
        $date=[
            'time'=>0,
            'name'=>'你没有开vip',
            'is_pay'=>'0'
        ];
        if ($new_time<0){
            switch ($vip_type){
                case 1:
                    $date=[
                        'time'=>0,
                        'name'=>'',
                        'is_pay'=>'0'
                    ];
                    break;
                case 2:
                    $date=[
                        'time'=>0,
                        'name'=>'',
                        'is_pay'=>'0'
                    ];
                    break;
                case 3:
                    $date=[
                        'time'=>0,
                        'name'=>'您的vip已到期',
                        'is_pay'=>'0'
                    ];
                    break;
                case 4:
                    $date=[
                        'time'=>0,
                        'name'=>'您的体验vip已到期',
                        'is_pay'=>'1'
                    ];
                    break;

            }
        }else{
//           if ($new_time>86400){
            if ($vip_type==4){
                $day=ceil($new_time/86400);
                $date=[
                    'time'=>$day,
                    'name'=>'您的体验vip还剩 '.$day.' 天',
                    'is_pay'=>'1'
                ];
            }


//               return $this->writeJson(200,$date,'ok');
//           }else if ($new_time<86400 && $new_time>3600){
//               $day=ceil($new_time/3600);
//               $date=[
//                   'time'=>$day,
//                   'name'=>'小时'
//               ];
//               return $this->writeJson(200,$date,'ok');
//           }else if ($new_time<3600){
//
//           }
        }
        return $date;
    }
}